<?php

namespace utils;

use think\facade\Config;
use think\facade\Lang;
use think\Response;

/**
 * Json输出类
 * Class Json
 * @package home\utils
 */
class Json
{
    private $code = 200;

    public function code(int $code): self
    {
        $this->code = $code;
        return $this;
    }

    public function make(int $code, string $msg, ?array $data = []): Response
    {
        $request = app()->request;
        $res = compact('code', 'msg');
        if(empty($data)){
            $data = (object)[];
        }
        $res['data'] = $data;

        if ($res['msg'] && !is_numeric($res['msg'])) {
            if (!$range = $request->get('lang')) {
                $range = $request->cookie(Config::get('lang.cookie_var'));
            }
            $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
        }
        return Response::create($res, 'json', $this->code);
    }

    public function success($msg = 'ok', ?array $data =[]): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }

        return $this->make(200, $msg, $data);
    }

    public function successful(...$args): Response
    {
        return $this->success(...$args);
    }

    public function fail($msg = 'fail', ?array $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }

        return $this->make(400, $msg, $data);
    }

    public function status($code, $msg, $result = [])
    {
        $code = strtoupper($code);
        if (is_array($msg)) {
            $result = $msg;
            $msg = 'ok';
        }
        return $this->success($msg, compact('code', 'result'));
    }

    /**
     * 返回json
     * @param int $code
     * @param string $msg
     * @param array|null $data
     * @return Response
     */
    public function json_success($msg = 'ok', ?array $data = null, $code = 200): Response
    {
        if (is_array($msg)) {
            $data = !isset($msg['data']) && !isset($msg['msg']) ? $msg : (isset($msg['data']) ? $msg['data'] : null);
            $code = isset($msg['code']) ? $msg['code'] : 200;
            $msg = isset($msg['msg']) ? $msg['msg'] : 'ok';
        }
        return $this->make($code, $msg, $data);
    }

    /**
     * 返回json
     * @param int $code
     * @param string $msg
     * @param array|null $data
     * @return Response
     */
    public function json_error($msg = 'error', $code = 500, array $data = null): Response
    {
        if (is_array($msg)) {
            $data = !isset($msg['data']) && !isset($msg['msg']) ? $msg : (isset($msg['data']) ? $msg['data'] : null);
            $code = isset($msg['code']) ? $msg['code'] : 500;
            $msg = isset($msg['msg']) ? $msg['msg'] : 'ok';
        }
        return $this->make($code, $msg, $data);
    }
}
